package cmd

import (
	"fmt"
	"os"
	"os/exec"
	"sync"

	ckeadmapi "ckeadm/cmd/apis"
	"ckeadm/cmd/runner"
	"ckeadm/constants"
	"github.com/sirupsen/logrus"
	"github.com/urfave/cli"
)

func StopCommand() cli.Command {
	var stopFlags = []cli.Flag {
		runner.ConfigPathFlag,
		runner.PrivateKey,
		runner.LogLevelFlag,
	}

	return cli.Command {
		Name:   "stop",
		Usage:  "Bring the cluster stopped",
		Action: runStop,
		Flags:  stopFlags,
	}
}


// runKubeletStart executes kubelet start logic.
func runStop(ctx *cli.Context) error {
	config, err := runner.GetConfigFromFile(ctx.String("f"))
	if err != nil {
		return fmt.Errorf("error while get config from %s, err: %s", ctx.String("f"), err.Error())
	}
	logrus.SetLevel(logrus.Level(ctx.Int("v")))

	var keyfile string
	if keyfile, err = runner.GetPrivateKeyFile(ctx.String("private-key")); err != nil {
		return fmt.Errorf("error while get set connection private key, err: %s", err.Error())
	}
	if ctx.String("private-key") == constants.EmptyString {
		defer os.Remove(keyfile)
	}

	if len(config.Nodes) == 0 {
		fmt.Println("No resources found in this configration.")
		return nil
	}

	// #nosec
	exec.Command("docker", "stop", "-t", "1", constants.CkeDeployContainerName + "-" + config.ClusterName).Run()
	logrus.Infof("main progress has been stopped.\n")

	wg := sync.WaitGroup{}
	wg.Add(len(config.Nodes))
	for _, node := range config.Nodes {
		go func(node ckeadmapi.CkeConfigNode) {
			_ = CkectlStop(node.Address, keyfile)
			logrus.Infof("%s installing has been stopped.\n", node.Name)
			wg.Done()
		}(node)
	}
	wg.Wait()

	return nil
}

func CkectlStop(ip string, privatekey string) error {
	var containerStop = fmt.Sprintf(`docker ps | grep %s | awk '{print $1}' | xargs docker stop -t 1`, constants.CkectlContainerName)
	// #nosec
	return exec.Command("ssh", ip, "-o", "StrictHostKeyChecking=no", "-i", privatekey, "-t", `ps -ef | grep "ckectl up" | grep -v grep | awk '{print $2}' | xargs -l kill -9; ` + containerStop).Run()
}